package org.nerve.study.sprider.common;

import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * org.nerve.study.sprider.common
 * Created by zengxm on 2016/3/17 0017.
 */
public final class StringUtil {
	public static String extractDomain(String getUrl) {
		//获取主域名
		Pattern p = Pattern.compile("(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv|la|onion)", Pattern.CASE_INSENSITIVE);
		Matcher matcher = p.matcher(getUrl);

		return matcher.find()?matcher.group():getUrl;
	}

	public static String getDomain(String url){
		String domain=extractDomain(url);
		return url.substring(0, url.indexOf(domain)+domain.length());
	}

	public static String md5(String str){
		MessageDigest messageDigest = getMessageDigest();
		byte[] digest;
		try {
			digest = messageDigest.digest(str.getBytes());
		} catch (Exception e) {
			throw new IllegalStateException("UTF-8 not supported!");
		}
		return new String(Hex.encodeHex(digest));
	}

	protected static final MessageDigest getMessageDigest() {
		String algorithm = "MD5";
		try {
			return MessageDigest.getInstance(algorithm);
		} catch (NoSuchAlgorithmException e) {
			throw new IllegalArgumentException("No such algorithm ["
					+ algorithm + "]");
		}
	}
}
